'use client';

import type { TMetadata } from '@/types';
import { useQuery } from '@tanstack/react-query';
import { clientQueryAllSection } from '@/services/api';
import type { ISectionClient, ISectionGroup, IUser } from '@/interfaces';
import ErrorPage from '@/app/[locale]/error/error';
import LoadPage from '@/app/[locale]/load/load';
import Image from 'next/image';
import Link from 'next/link';
import { getCover, getUserAvatar } from '@/lib/tool';
import FooterH5IcpPage from '@/app/[locale]/mobile/footerH5Icp';
import FooterH5Page from '@/app/[locale]/mobile/footerH5';
import classNames from 'classnames';
import Nodata from '@/app/[locale]/common/nodata/nodata';

export default function SectionH5Page({ metadata }: { metadata: TMetadata }) {
  return (
    <>
      <Section metadata={metadata} />
      <FooterH5IcpPage metadata={metadata} />
      <FooterH5Page metadata={metadata} />
    </>
  );
}

const Section = ({ metadata }: { metadata: TMetadata }) => {
  const clientQueryAllSectionQuery = useQuery(
    metadata.all['sections'].k,
    async () => {
      return (await clientQueryAllSection()) as ISectionClient[];
    },
    {
      initialData: metadata.all['sections'].v as ISectionClient[],
    },
  );

  if (clientQueryAllSectionQuery.data) {
    const data = clientQueryAllSectionQuery.data;
    const sectionGroups = data
      .filter((item) => !!item.sectionGroup)
      .filter(
        (item, index, array) =>
          array.findIndex(
            (value) => value.sectionGroup!.id === item.sectionGroup!.id,
          ) === index,
      )
      .map((item) => {
        const sectionGroup = item.sectionGroup!;
        const _sections: ISectionClient[] = [];
        data.forEach((value) => {
          if (value.sectionGroup?.id === sectionGroup.id) {
            _sections.push(value);
          }
        });
        sectionGroup.sections = _sections;
        return sectionGroup;
      });
    const otherSections = data.filter((item) => !item.sectionGroup);

    return (
      <div className="col p-2">
        <div className="card rounded-5 border-0">
          <div className="card-body overflow-hidden">
            <div className="vstack gap-4">
              {sectionGroups.map((item, index) => {
                return (
                  <Item
                    key={item.id}
                    item={item}
                    index={index}
                    metadata={metadata}
                  />
                );
              })}

              {otherSections.length > 0 &&
                [
                  {
                    id: -1,
                    name: '其他内容',
                  },
                ].map((item, index) => {
                  return (
                    <Item
                      key={item.id}
                      item={item as ISectionGroup}
                      index={index}
                      metadata={metadata}
                      firstRowLine={sectionGroups.length > 0}
                      vstack={sectionGroups.length === 0}
                      showNav={sectionGroups.length > 0}
                      items={otherSections}
                    />
                  );
                })}

              <div></div>
            </div>

            {sectionGroups.length === 0 && otherSections.length === 0 && (
              <Nodata />
            )}
          </div>
        </div>
      </div>
    );
  }

  if (clientQueryAllSectionQuery.error) {
    return <ErrorPage error={clientQueryAllSectionQuery.error} />;
  }

  return <LoadPage />;
};

const Item = ({
  item,
  index,
  metadata,
  firstRowLine,
  items,
  vstack,
  showNav = true,
}: {
  item: ISectionGroup;
  index: number;
  metadata: TMetadata;
  firstRowLine?: boolean;
  items?: ISectionClient[];
  vstack?: boolean;
  showNav?: boolean;
}) => {
  return (
    <div className="row gap-4">
      {firstRowLine && (
        <div
          className="col-12 yw-bg w-100"
          style={{ height: '0.5rem', transform: 'scale(1.1)' }}
        ></div>
      )}
      {!firstRowLine && index !== 0 && (
        <div
          className="col-12 yw-bg w-100"
          style={{ height: '0.5rem', transform: 'scale(1.1)' }}
        ></div>
      )}

      {showNav && (
        <div className="col-12 user-select-none d-flex align-items-center justify-content-between">
          <div className="h4">{item.name}</div>
          <div className="text-muted">
            <i className="bi bi-arrow-right fs-4"></i>
          </div>
        </div>
      )}

      <div
        className={classNames(
          'col-12 pb-3 gap-4',
          vstack
            ? 'vstack'
            : 'd-flex align-items-center flex-nowrap text-nowrap overflow-x-auto',
        )}
      >
        {(items ? items : item.sections!).map((sectionItem) => {
          return (
            <div
              key={sectionItem.id}
              className="vstack gap-4 shadow-sm px-4 py-2 rounded-4"
            >
              <Cover
                id={sectionItem.id}
                cover={sectionItem.cover}
                metadata={metadata}
              />

              <Admins
                id={sectionItem.id}
                items={(sectionItem as ISectionClient).admins}
                metadata={metadata}
              />

              <div className="vstack gap-2">
                <Name id={sectionItem.id} name={sectionItem.name} />

                <Overview overview={sectionItem.overview} />
              </div>

              <End id={sectionItem.id} />
            </div>
          );
        })}
      </div>
    </div>
  );
};

const Cover = ({
  id,
  cover,
  metadata,
}: {
  id: number;
  cover: string | undefined;
  metadata: TMetadata;
}) => {
  const env = metadata.env;

  return (
    <>
      {cover && (
        <div>
          <Link href={`/sections/${id}`}>
            <Image
              className="rounded object-fit-contain w-auto"
              src={getCover(cover, metadata)}
              width={150}
              height={112}
              alt="cover"
              placeholder="blur"
              blurDataURL={env.APP_BLUR_DATA_URL}
            />
          </Link>
        </div>
      )}
    </>
  );
};

const Admins = ({
  id,
  items = [],
  metadata,
}: {
  id: number;
  items?: IUser[];
  metadata: TMetadata;
}) => {
  const env = metadata.env;

  return (
    <>
      {items.length > 0 && (
        <div className="position-relative w-100" style={{ height: 48 }}>
          {items.slice(0, 5).map((item, index) => {
            return (
              <div
                key={item.id}
                className="position-absolute"
                style={{
                  left: index * 33,
                  zIndex: index + 1,
                }}
              >
                <Link
                  title={`${item.alias}(${item.id})`}
                  className="text-decoration-none text-decoration-underline-hover link-secondary"
                  href={`/users/${item.id}`}
                >
                  {item.details && item.details.smallAvatarUrl ? (
                    <Image
                      className="rounded-circle"
                      src={getUserAvatar(item, metadata).mediumAvatarUrl}
                      alt={item.alias || ''}
                      title={item.alias || ''}
                      placeholder="blur"
                      blurDataURL={env.APP_BLUR_DATA_URL}
                      width={48}
                      height={48}
                    />
                  ) : (
                    <Image
                      className="rounded-circle"
                      src="/images/avatar.png"
                      alt=""
                      placeholder="blur"
                      blurDataURL={env.APP_BLUR_DATA_URL}
                      width={48}
                      height={48}
                    />
                  )}
                </Link>
              </div>
            );
          })}

          {items.length > 5 && (
            <div
              className="position-absolute fs-5 link-secondary"
              style={{ left: 198, top: 6 }}
            >
              <Link
                className="text-decoration-none text-decoration-underline-hover link-secondary"
                href={`/sections/${id}`}
              >
                +{items.length - 5}
              </Link>
            </div>
          )}
        </div>
      )}
    </>
  );
};

const Name = ({ id, name }: { id: number; name: string }) => {
  return (
    <Link
      href={`/sections/${id}`}
      className="text-reset text-decoration-none text-decoration-underline-hover"
    >
      {name}
    </Link>
  );
};

const Overview = ({ overview }: { overview: string | undefined }) => {
  return (
    <>
      {overview && (
        <div
          style={{
            width: 112,
          }}
          className="text-truncate text-secondary"
          dangerouslySetInnerHTML={{
            __html: overview,
          }}
        ></div>
      )}
    </>
  );
};

const End = ({ id }: { id: number }) => {
  return (
    <div>
      <Link
        href={`/sections/${id}`}
        className="text-decoration-none position-relative"
      >
        进入内容
        <i
          className="bi bi-arrow-up-short align-middle d-inline-block fs-4"
          style={{ transform: 'rotate(45deg)' }}
        ></i>
      </Link>
    </div>
  );
};
